<template>
  <!-- JSON编辑器 -->
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import "script-loader!json-lint";

import * as CodeMirror from "codemirror";
import "codemirror/addon/lint/lint.css";
import "codemirror/lib/codemirror.css";
// 主题
import "codemirror/theme/rubyblue.css";

import "codemirror/mode/javascript/javascript";

export default {
  name: "JsonEditor",
  /* eslint-disable vue/require-prop-types */
  props: {
    value: {
      type: [Object, String],
      default: ""
    }
  },
  data() {
    return {
      jsonEditor: false
    };
  },
  watch: {
    value(value) {
      const editorValue = this.jsonEditor.getValue();
      if (value !== editorValue) {
        this.jsonEditor.setValue(JSON.stringify(this.value, null, 2));
      }
    }
  },
  mounted() {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      // 是否显示行号
      lineNumbers: false,
      mode: "application/json",
      gutters: ["CodeMirror-lint-markers"],
      theme: "rubyblue",
      lint: true
    });

    this.jsonEditor.setValue(JSON.stringify(this.value, null, 2));
    this.jsonEditor.on("change", cm => {
      this.$emit("changed", cm.getValue());
      this.$emit("input", cm.getValue());
    });
  },
  methods: {
    getValue() {
      return this.jsonEditor.getValue();
    }
  }
};
</script>

<style lang="scss" scoped>
.json-editor {
  height: 100%;
  position: relative;

  // ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }

    .CodeMirror-scroll {
      min-height: 300px;
    }

    .cm-s-rubyblue span.cm-string {
      color: #F08047;
    }
  // }
}
</style>
